// store/index.js
import { createStore } from 'vuex'

let lifeData = {}
try {
  lifeData = uni.getStorageSync('lifeData') || {}
} catch(e) {}

const saveStateKeys = ['vuex_user']

const saveLifeData = function(key, value) {
  if (saveStateKeys.indexOf(key) !== -1) {
    const tmpLifeData = { ...uni.getStorageSync('lifeData') || {} }
    tmpLifeData[key] = value
    uni.setStorageSync('lifeData', tmpLifeData)
  }
}

const store = createStore({
  state() {
    return {
      vuex_user: lifeData.vuex_user || { name: '图鸟' },
      vuex_version: "1.0.0",
      vuex_custom_nav_bar: true,
      vuex_status_bar_height: 0,
      vuex_custom_bar_height: 0
    }
  },
  mutations: {
    $tStore(state, payload) {
      const nameArr = payload.name.split('.')
      let saveKey = ''
      const len = nameArr.length
      if (len >= 2) {
        let obj = state[nameArr[0]]
        for (let i = 1; i < len - 1; i++) {
          obj = obj[nameArr[i]]
        }
        obj[nameArr[len - 1]] = payload.value
        saveKey = nameArr[0]
      } else {
        state[payload.name] = payload.value
        saveKey = payload.name
      }
      saveLifeData(saveKey, state[saveKey])
    }
  },
  actions: {}
})

export default store